<template>
	<Modal :title="type=='报工打印'?'标签打印':'标签补印'" ref="popup1" width="80%" @confirm="confirm1" :autoClose="false" :loading='printLoading'>
		<FormWrap height="50vh">
			<u--form labelPosition="top" labelAlign="left" :model="model" :rules="rules" ref="uForm" labelWidth="12rem"
				:labelStyle="{'margin-bottom' : labelPosition === 'top' ? '2rem' : '0'}" style="padding: 0 5rem;">
				<u-row justify="space-between">
					<u-col span="5">
						<u-form-item label="标签类型" prop="labelType" required class="label-fwn">
							<uni-data-select v-model="model.labelType" :modelValue="model.labelType"
								:localdata="labelTypes" format="{label}" placeholder="请选择"
								:clear="false"></uni-data-select>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="工单号" prop="workCode" required class="label-fwn">
							<InputField v-model="model.workCode"></InputField>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between">
					<u-col span="5">
						<u-form-item label="产品编号" prop="materialCode" required class="label-fwn">
							<InputField v-model="model.materialCode"></InputField>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="产品名称" prop="materialName" required class="label-fwn">
							<InputField v-model="model.materialName"></InputField>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between">
					<u-col span="5">
						<u-form-item label="产品型号" prop="materialModel" class="label-fwn">
							<InputField v-model="model.materialModel" disabled></InputField>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="装箱数量" prop="packingQuantity" required class="label-fwn">
							<InputNumberField :decimal="3" :halfAdjust="false" :disabled="printLoading" v-model="model.packingQuantity" :min="1" :max="99999999.999">
							</InputNumberField>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between">
					<u-col span="5">
						<u-form-item label="张数" prop="printQuantity" required class="label-fwn">
							<InputNumberField v-model="model.printQuantity" :min="1" :max="999"></InputNumberField>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="工号" prop="empno" required class="label-fwn">
							<InputField v-model="model.empno"></InputField>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between">
					<u-col span="5">
						<u-form-item label="生产日期" prop="shiftTime" required class="label-fwn">
							<DatePicker v-model="model.shiftTime" @change="shiftTimeChange"></DatePicker>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="客户" prop="custom" class="label-fwn">
							<InputField v-model="model.custom" disabled></InputField>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between" v-if="model.labelType !== '老厂产品标签'">
					<u-col span="5" v-if="model.labelType === '条料标签'">
						<u-form-item label="料位" prop="materialLevel" required class="label-fwn">
							<InputField v-model="model.materialLevel"></InputField>
						</u-form-item>
					</u-col>
					<u-col span="5" v-if="model.labelType == '退火标签'">
						<u-form-item label="炉号" prop="heatNumber" class="label-fwn">
							<SingleSelect v-model="model.heatNumber" :list="heatNumberList" mode="single" />
						</u-form-item>
					</u-col>
					<u-col span="5" v-else>
						<u-form-item label="班次" prop="shift" class="label-fwn">
							<SingleSelect v-model="model.shift" :list="shifts" mode="single" />
						</u-form-item>
					</u-col>
					
					<u-col span="5" v-if="model.labelType !== '条料标签'">
						<u-form-item label="材料牌号" prop="productGrade" class="label-fwn">
							<InputField v-model="model.productGrade"></InputField>
						</u-form-item>
					</u-col>
					
				</u-row>
				<template v-if="model.labelType === '老厂产品标签'">
					<u-row justify="space-between">
						<u-col span="5">
							<u-form-item label="内外模" prop="modelType" class="label-fwn">
								<SingleSelect v-model="model.modelType" :list="modelTypeList" format="{label}"
									mode="single"></SingleSelect>
							</u-form-item>
						</u-col>
						<u-col span="5">
							<u-form-item label="材料牌号" prop="customMark" class="label-fwn">
								<InputField v-model="model.customMark"></InputField>
							</u-form-item>
						</u-col>
					</u-row>
					<u-row justify="space-between">
						<u-col span="5">
							<u-form-item label="天数" prop="shiftTime" class="label-fwn">
								<InputField disabled :value="getYearOfDay(model.shiftTime)"></InputField>
							</u-form-item>
						</u-col>
					</u-row>
				</template>
				<u-row justify="space-between" v-if="model.labelType === '管品合格证'">
					<u-col span="5">
						<u-form-item label="合同编号" prop="contractNumber" required class="label-fwn">
							<InputField v-model="model.contractNumber"></InputField>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="包装编号" prop="packagingNumber" required class="label-fwn">
							<InputField v-model="model.packagingNumber"></InputField>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between" v-if="model.labelType === '管品合格证'">
					<u-col span="5">
						<u-form-item label="检验" prop="test" class="label-fwn">
							<InputField v-model="model.test"></InputField>
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="检验日期" prop="testTime" class="label-fwn">
							<DatePicker v-model="model.testTime"></DatePicker>
						</u-form-item>
					</u-col>
				</u-row>
				<u-row justify="space-between" v-if="model.tagType === '管品合格证'">
					<u-col span="12">
						<u-form-item label="备注" prop="remarks" class="label-fwn">
							<InputField v-model="model.remarks" :maxlength="100" />
						</u-form-item>
					</u-col>
				</u-row>
			</u--form>
		</FormWrap>
	</Modal>
</template>

<script>
	import FormWrap from '@/components/formWrap/index.vue';
	import InputField from '@/components/formField/inputField/index.vue';
	import InputCaptcheField from '@/components/formField/inputCaptcheField/index.vue';
	import InputNumberField from '@/components/formField/inputNumberField/index.vue';
	import NumberBoxField from '@/components/formField/numberBoxField/index.vue';
	import RemoteMultipleSelect from '@/components/formField/remoteMultipleSelect/index.vue';
	import SingleSelect from '@/components/formField/singleSelect/index.vue';
	import DatePicker from '@/components/formField/datePicker/index.vue';
	import Modal from '@/components/modal/index.vue';
	import fetch from "@/utils/fetch";
	import util from "@/utils/util";

	import {
		timeIsBetweenTimeRange
	} from "@/utils/date";
	import {
		getDevice
	} from "@/store/user.js";
	import filter from "@/utils/filter";

	export default {
		components: {
			FormWrap,
			InputField,
			InputCaptcheField,
			InputNumberField,
			NumberBoxField,
			RemoteMultipleSelect,
			SingleSelect,
			DatePicker,
			Modal,
		},
		props: {
			labelTypes: {
				type: Array,
				default () {
					return [{
							label: '产品标签',
							value: '产品标签',
						},
						{
							label: '老厂产品标签',
							value: '老厂产品标签',
						},
						{
							label: '条料标签',
							value: '条料标签',
						},
						{
							label: '不良品标签',
							value: '不良品标签',
						},
						{
							label: '退火标签',
							value: '退火标签',
						},
					]
				}
			},
		},
		data() {
			return {
				type:'',
				printLoading: false,
				labelPosition: 'left',
				shifts: [],
				model: {
					labelType: '产品标签', // default
					shift: '',
				},
				rules: {
					'labelType': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'workCode': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'materialCode': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'materialName': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'packingQuantity': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'printQuantity': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'empno': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'shiftTime': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'materialLevel': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'contractNumber': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'packagingNumber': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
				},
				modelTypeList: [{
						label: "内",
						value: '内',
					},
					{
						label: "外",
						value: '外',
					},
				],
			}
		},
		  computed: {
		    heatNumberList() {
		      let res = [];
		      if (getDevice().deviceNo) {
		       const code=getDevice().deviceNo;
		       switch (code) {
		        case 'I1':
		          res=[{label:'1',value:'1'},{label:'2',value:'2'},{label:'3',value:'3'},{label:'4',value:'4'}]
		          break;
		        case 'I2':
		          res=[{label:'5',value:'5'},{label:'6',value:'6'}]
		          break;
		        case 'I10':
		          res=[{label:'7',value:'7'}]
		          break;
		       }
		       return res;
		      }else return res
		    }
		  },
		methods: {
			getYearOfDay(time) {
				function isLeapYear(year) {
					return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
				}

				function dayOfYear(date) {
					const year = date.getFullYear();
					const month = date.getMonth();
					const day = date.getDate();

					const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

					if (isLeapYear(year)) {
						daysInMonth[1] = 29;
					}

					let count = 0;
					for (let i = 0; i < month; i++) {
						count += daysInMonth[i];
					}

					return count + day;
				}
				return dayOfYear(new Date(time));
			},
			open(item,type) {
				this.model = {
					...this.model,
					...item,
				};
				this.type=type;
				this.getShiftList(() => {
					this.$refs.popup1.open();
				});
			},
			async getSubsequentOrder(orderCode){
				return await fetch('get','/dms/pRoductionReporting/querySubsequentOrder',null,{orderCode})
			},
			async confirm1(next) {
				const orderInfo=await this.getSubsequentOrder(this.model.orderCode)
				this.$refs['uForm'].validate().then((valid) => {
					if (valid) {
						const data = {
							...orderInfo,
							"workCode": this.model.workCode,
							"shiftId": this.model.shiftId,
							"shift": this.model.shift,
							"shiftTime": this.model.shiftTime,
							"reportingMethod": this.model.reportingMethod,
							"operatorNumber": this.model.operatorNumber,
							"operator": this.model.operator,
							"reportedQuantity": this.model.reportedQuantity,
							"warehouseId": this.model.warehouseId,
							"reportingTime": this.model.reportingTime,
							"orderCode": this.model.orderCode,
							"functionalLocation": this.model.functionalLocation,
							"functionalLocationName": this.model.functionalLocationName,
							"batchNumber": this.model.batchNumber,
							"deviceNo": this.model.deviceNo,
							"moldCode": this.model.moldCode,
							"materialCode": this.model.materialCode,
							"materialName": this.model.materialName,
							"materialModel": this.model.materialModel,
							"weight": this.model.weight,
							"weightUnit": this.model.weightUnit,
							"mode": this.model.mode,
							"reportingOperator": this.model.reportingOperator,
							"reportingWeightUnits": this.model.reportingWeightUnits,
							"status": this.model.status,
							"rueck": this.model.rueck,
							"rmzhl": this.model.rmzhl,
							"empno": this.model.empno,
							"materialMark": this.model.materialMark,
							"customMaterialCode": this.model.customMaterialCode,
							"productionProcesses": this.model.productionProcesses,
							"scene01": this.model.scene01,
							"deviceCode": this.model.deviceCode,
							"printQuantity": this.model.printQuantity,
							"labelType": this.model.labelType,
							"packingQuantity": this.model.packingQuantity,
							"reportingId": this.model.id,
							'productGrade':this.model.productGrade,
							'customMark':this.model.customMark,
							'heatNumber':this.model.heatNumber,
							"modelType": this.model.modelType == '内' ? 0 : this.model.modelType == '外' ? 1 :
								null,
							"tagSerialNumber": this.getTagSerialNumber()
						};
						console.log(JSON.stringify(data))
						this.printLoading=true;
						fetch('post', this.type=='报工打印'?'/dms/labelPrinting/addLabelPrinting':'/dms/labelPrinting/reprintLabelPrinting', null, data)
							.then((res) => {
								this.printLoading=false;
								fetch('post', '/dms/labelPrinting/print', null, res).then(() => {
									this.$toast('已发送打印任务');
									this.$refs.popup1.close();
									next();
								})
							}).finally(()=>{
								this.printLoading=false;
							});
					}
				});
			},
			getTagSerialNumber() {
				const arr = [];
				for (let i = 0; i < this.model.printQuantity; i++) {
					arr.push(util.getUuid(14));
				}
				return arr.join(',');
			},
			shiftTimeChange() {
				this.getShiftList();
			},
			getShiftList(cb) {
				fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: getDevice().deviceNo,
					shiftDate: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
				}).then((res) => {
					this.shifts = res.map((item) => ({
						label: item.shift,
						value: item.shift,
					}));
					if (this.shifts.length !== 0) {
						const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
							item.shiftStartTime,
							item.shiftEndTime));
						if (has)
							this.model.shift = has.shift;
						else
							this.model.shift = this.shifts[0].value;
					} else {
						this.model.shift = null;
					}
					cb && cb();
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.table-demo {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.table {
		width: 100%;
		display: flex;
		flex-direction: column;
		border: 1px solid #ecf0f2;
		border-radius: 2rem;
		overflow: hidden;
		position: relative;

		.table-loading {
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			background: rgba(255, 255, 255, 0.8);
		}

		.table-empty {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 4rem 0;
			font-size: 2rem;
		}

		.table-tr {
			display: flex;
			flex-direction: row;
			border-top: 1px solid #ecf0f2;
		}

		.table-th {
			flex: 1;
			background: #edf1f3;
			font-size: 2rem;
			text-align: center;
			padding: 2rem 0;
			overflow: hidden;
		}

		.table-td {
			flex: 1;
			font-size: 2rem;
			text-align: center;
			padding: 1.8rem 0;
			overflow: hidden;
		}

		.text-overflow-ellipsis {
			width: 80%;
			padding: 0;
			text-overflow: ellipsis;
			overflow: hidden;
			white-space: nowrap;
			margin: 0 auto;
		}
	}
</style>